package game.resources;

import java.sql.SQLException;
import server.DBLogic;

public class Chat {
	
	int gameID;
	int numOfPlayers;
	DBLogic dbl;
	
	private final static String SEPARATOR = "^";
	
	private Boolean isBetween(int num) {
		return (num > 0 && num <= numOfPlayers);
	}

	public Chat(int gameID) {
		this.gameID = gameID;
		
		dbl = new DBLogic(); 
		dbl.InitDBConnection();
		try {
            numOfPlayers = dbl.queryGameNumberOfPlayers(gameID);
        } catch (SQLException e) {
            
        } finally {
            dbl.ShutDBConnection();
        }
		
	}
	
	public boolean init() {
		dbl.InitDBConnection();
		for (int i=1;i<=6;i++) {
			if (!dbl.postChatMsg(gameID,i,"")) {
				dbl.ShutDBConnection();
				return false;
			}
		}
		dbl.ShutDBConnection();
		return true;
	}
	
	public boolean sendMsg(int playerIndex,String playerName,String msg) {
		if (!isBetween(playerIndex))
			return false;
		dbl.InitDBConnection();
		String stackedMsg;
		msg = playerName + " > " + msg;
		for (int i=1;i<=numOfPlayers;i++) {
			stackedMsg = null;
			try {
				stackedMsg = dbl.queryChatMsg(gameID, i);
			} catch (SQLException e) {
				dbl.ShutDBConnection();
				return false;
			}
			if (stackedMsg == null)  {
				dbl.ShutDBConnection();
				return false;
			}
			stackedMsg += SEPARATOR;
			stackedMsg += msg;
			if (!dbl.postChatMsg(gameID,i,stackedMsg)) {
				dbl.ShutDBConnection();
				return false;
			}
		}
		dbl.ShutDBConnection();
		return true;
	}
	
	public String recieveMsg(int playerIndex) {
		if (!isBetween(playerIndex))
			return null;
		dbl.InitDBConnection();
		String msg = null;
		try {
			msg = dbl.queryChatMsg(gameID, playerIndex);
		} catch (SQLException e) {
			dbl.ShutDBConnection();
			return null;
		}
		if (msg == null) {
			dbl.ShutDBConnection();
			return null;
		}

		boolean check = dbl.postChatMsg(gameID,playerIndex, "");
		dbl.ShutDBConnection();
		if (!check)
			return null;
		return msg;
	}
}
